package com.itheima.wisdomnext.Handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.wisdomnext.entity.Message;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketHandler extends TextWebSocketHandler {

    // 存储用户的 WebSocket 连接：key 形如 "user_1001" 或 "admin_2001"，value 是对应的 WebSocketSession
    private static final Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 服务器主动推送消息给客户端（Controller 或 Service 可以调用此方法）
     */
    public static void dispatchMessage(Message msg) {
        try {
            // 将 Message 对象转换成 JSON 字符串
            String payload = new ObjectMapper().writeValueAsString(msg);

            if (msg.getRecipientId() == null) {
                // recipientId 为空，说明是广播给所有管理员
                for (Map.Entry<String, WebSocketSession> entry : sessionMap.entrySet()) {
                    if (entry.getKey().startsWith("admin_") && entry.getValue().isOpen()) {
                        entry.getValue().sendMessage(new TextMessage(payload));
                    }
                }
            } else {
                // 精准推送给某个用户
                String key = "user_" + msg.getRecipientId();
                WebSocketSession session = sessionMap.get(key);
                System.out.println(sessionMap);
                if (session != null && session.isOpen()) {
                    session.sendMessage(new TextMessage(payload));
                }
            }
        } catch (Exception e) {
            e.printStackTrace(); // 错误处理
        }
    }

    /**
     * 当客户端连接建立成功时触发
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从 URI 获取参数，如：?userId=1001&role=user
        String query = session.getUri().getQuery();

        if (query != null) {
            Map<String, String> paramMap = parseQuery(query);
            String userId = paramMap.get("userId");
            String role = paramMap.get("role"); // 角色：user 或 admin

            if (userId != null && role != null) {
                // 拼接 key，例如 "user_1001" 或 "admin_2001"
                String key = role + "_" + userId;

                // 检查是否已经有一个活跃连接
                if (sessionMap.containsKey(key)) {
                    WebSocketSession existingSession = sessionMap.get(key);
                    if (existingSession != null && existingSession.isOpen()) {
                        // 如果存在，关闭旧的连接
                        existingSession.close(CloseStatus.NORMAL);
                        System.out.println("关闭旧的连接：userId=" + userId);
                    }
                }

                // 保存新的连接
                sessionMap.put(key, session);
                System.out.println("连接建立：userId=" + userId + "，身份=" + role);
            }
        }
    }

    /**
     * 当客户端发送文本消息时触发
     */
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("收到消息: " + payload);

        // 将 JSON 字符串转换为 Message 对象
        Message msg = objectMapper.readValue(payload, Message.class);

        if (msg.getRecipientId() == null) {
            // 广播给所有管理员
            for (Map.Entry<String, WebSocketSession> entry : sessionMap.entrySet()) {
                if (entry.getKey().startsWith("admin_")) {
                    entry.getValue().sendMessage(new TextMessage(payload));
                }
            }
        } else {
            // 精确推送给某个普通用户
            String targetKey = "user_" + msg.getRecipientId();
            WebSocketSession targetSession = sessionMap.get(targetKey);
            if (targetSession != null && targetSession.isOpen()) {
                targetSession.sendMessage(new TextMessage(payload));
            }
        }
    }

    /**
     * 当连接关闭时触发
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 只移除当前关闭的连接
        sessionMap.entrySet().removeIf(entry -> entry.getValue().getId().equals(session.getId()));
        System.out.println("连接关闭: " + session.getId());
    }

    /**
     * 向所有普通用户广播系统公告
     */
    public void broadcastAnnouncementToAllUsers(String message) {
        for (Map.Entry<String, WebSocketSession> entry : sessionMap.entrySet()) {
            if (entry.getKey().startsWith("user_")) {
                try {
                    entry.getValue().sendMessage(new TextMessage(message));
                } catch (Exception e) {
                    e.printStackTrace(); // 忽略发送失败
                }
            }
        }
    }

    /**
     * 将 URL 参数字符串（例如：userId=1001&role=user）解析为 Map
     */
    private Map<String, String> parseQuery(String query) {
        Map<String, String> map = new HashMap<>();
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            String[] kv = pair.split("=");
            if (kv.length == 2) {
                map.put(kv[0], kv[1]);
            }
        }
        return map;
    }
}
